﻿using Application.Common.Interfaces;
using Application.Features.Menus.DTOs;
using AutoMapper;
using Common.Attributes;
using Domain.Entities.Identity;
using Domain.ValueObjects;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System.ComponentModel;

namespace Application.Features.Menus.Commands.Update;

/// <summary>
/// 备份菜单
/// </summary>
[Map(typeof(Menu))]
[Description("备份菜单")]
[GroupDescription("菜单管理")]
public class BackupMenuDataToJsonCommand : IRequest<bool>
{
}

/// <summary>
/// 处理程序
/// </summary>
public class BackupMenuDataToJsonCommandHandler : IRequestHandler<BackupMenuDataToJsonCommand, bool>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;

    public BackupMenuDataToJsonCommandHandler(
        IApplicationDbContext context,
        IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(BackupMenuDataToJsonCommand request, CancellationToken cancellationToken)
    {
        var menus =await _context.Menus.ToListAsync();
        if (!menus.Any()) throw new Exception("没有需要备份的菜单数据");

        string json = JsonConvert.SerializeObject(_mapper.Map<IEnumerable<BackupMenuOutput>>(menus));

        var saveFilePath = Path.Combine(Directory.GetCurrentDirectory(), "menus.json");
        if (!File.Exists(saveFilePath)) 
            File.Create(saveFilePath).Close();

        File.WriteAllText(saveFilePath, json);

        return true;
    }
}